/**
 * ParamUtils.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-12-07 15:49:27 +0800 $
 * $Revision: 1402 $
 */
package com.myspace.common.util;

import javax.servlet.http.*;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;

public class ParamUtils {

	private static Logger LOG = Logger.getLogger(ParamUtils.class);

	public static String PARAM_PREFIX = "_";

	/**
	 * get parameter value from queryString
	 *
	 * @param queryString
	 * @param key
	 */
	public String parseQueryString(String queryString, String key) {
		if (queryString == null)
			return null;
		int begin = queryString.indexOf(key);
		if (begin < 0)
			return null;

		String qs = queryString.substring(queryString.indexOf(key)
				+ key.length() + 1);
		try {
			int next = qs.indexOf('&');
			if (next > 0) {
				qs = qs.substring(0, next);
				return java.net.URLDecoder.decode(qs, "ISO-8859-1");
			} else if (qs != null && next < 0 && qs.length() > 0) {
				return java.net.URLDecoder.decode(qs, "ISO-8859-1");
			}
		} catch (java.io.UnsupportedEncodingException e) {
			LOG.error(e);
		}
		return null;
	}

	/**
	 * Gets a parameter as a string.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param paramName
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getParameter(HttpServletRequest request,
			String paramName) {
		return getParameter(request, paramName, false);
	}

	/**
	 * Gets a parameter as a string.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param paramName
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getParameter(HttpServletRequest request,
			String paramName, boolean emptyStringsOK) {
		String temp = request.getParameter(paramName);
		if (temp != null) {
			if (temp.equals("") && !emptyStringsOK) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}

	/**
	 * Gets a parameter as a boolean.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param paramName
	 *            The name of the parameter you want to get
	 * @return True if the value of the parameter was "true", false otherwise.
	 */
	public static boolean getBooleanParameter(HttpServletRequest request,
			String paramName) {
		String temp = request.getParameter(paramName);
		if (temp != null && temp.equals("true")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets a parameter as a int.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param paramName
	 *            The name of the parameter you want to get
	 * @return The int value of the parameter specified or the default value if
	 *         the parameter is not found.
	 */
	public static int getIntParameter(HttpServletRequest request,
			String paramName, int defaultNum) {
		String temp = request.getParameter(paramName);
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
				LOG.error(ignored);
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	public static long getLongParameter(HttpServletRequest request,
			String paramName, long defaultNum) {
		String temp = request.getParameter(paramName);
		if (temp != null && !temp.equals("")) {
			long num = defaultNum;
			try {
				num = Long.parseLong(temp);
			} catch (Exception ignored) {
				LOG.error(ignored);
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	public static int[] getIntParameters(HttpServletRequest request,
			String paramName) {
		String[] temps = request.getParameterValues(paramName);
		if (temps == null)
			return null;
		ArrayList<Integer> al = new ArrayList<Integer>();
		for (int i = 0; i < temps.length; i++) {
			try {
				Integer one = Integer.valueOf(temps[i]);
				al.add(one);
			} catch (Exception e) {
				LOG.error(e);
			}
		}
		int[] ret = new int[al.size()];
		for (int i = 0; i < al.size(); i++) {
			ret[i] = ((Integer) al.get(i)).intValue();
		}
		return ret;
	}

	public static long[] getLongParameters(HttpServletRequest request,
			String paramName) {
		String[] temps = request.getParameterValues(paramName);
		if (temps == null)
			return null;
		ArrayList<Long> al = new ArrayList<Long>();
		for (int i = 0; i < temps.length; i++) {
			try {
				Long one = Long.valueOf(temps[i]);
				al.add(one);
			} catch (Exception e) {
				LOG.error(e);
			}
		}
		long[] ret = new long[al.size()];
		for (int i = 0; i < al.size(); i++) {
			ret[i] = ((Long) al.get(i)).longValue();
		}
		return ret;
	}

	/**
	 * Gets a checkbox parameter value as a boolean.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param paramName
	 *            The name of the parameter you want to get
	 * @return True if the value of the checkbox is "on", false otherwise.
	 */
	public static boolean getCheckboxParameter(HttpServletRequest request,
			String paramName) {
		String temp = request.getParameter(paramName);
		if (temp != null && temp.equals("on")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets a parameter as a string.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param attribName
	 *            The name of the parameter you want to get
	 * @return The value of the parameter or null if the parameter was not found
	 *         or if the parameter is a zero-length string.
	 */
	public static String getAttribute(HttpServletRequest request,
			String attribName) {
		return getAttribute(request, attribName, false);
	}

	/**
	 * Gets a parameter as a string.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param attribName
	 *            The name of the parameter you want to get
	 * @param emptyStringsOK
	 *            Return the parameter values even if it is an empty string.
	 * @return The value of the parameter or null if the parameter was not
	 *         found.
	 */
	public static String getAttribute(HttpServletRequest request,
			String attribName, boolean emptyStringsOK) {
		String temp = (String) request.getAttribute(attribName);
		if (temp != null) {
			if (temp.equals("") && !emptyStringsOK) {
				return null;
			} else {
				return temp;
			}
		} else {
			return null;
		}
	}

	/**
	 * Gets an attribute as a boolean.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param attribName
	 *            The name of the attribute you want to get
	 * @return True if the value of the attribute is "true", false otherwise.
	 */
	public static boolean getBooleanAttribute(HttpServletRequest request,
			String attribName) {
		String temp = (String) request.getAttribute(attribName);
		if (temp != null && temp.equals("true")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Gets an attribute as a int.
	 *
	 * @param request
	 *            The HttpServletRequest object, known as "request" in a JSP
	 *            page.
	 * @param attribName
	 *            The name of the attribute you want to get
	 * @return The int value of the attribute or the default value if the
	 *         attribute is not found or is a zero length string.
	 */
	public static int getIntAttribute(HttpServletRequest request,
			String attribName, int defaultNum) {
		String temp = (String) request.getAttribute(attribName);
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
				LOG.error(ignored);
			}
			return num;
		} else {
			return defaultNum;
		}
	}

	@SuppressWarnings("unchecked")
	public static String getParamsByPrefix(HttpServletRequest request,
			String prefix, String encoding) {
		if (prefix == null || prefix.trim().length() == 0) {
			prefix = PARAM_PREFIX;
		}
		StringBuffer buffer = new StringBuffer();
		Map<String, String> paramMap = (Map<String, String>) request
				.getParameterMap();
		if (paramMap != null && paramMap.size() > 0) {
			for (Entry entry : paramMap.entrySet()) {
				String key = (String) entry.getKey();
				String value = (String) entry.getKey();
				if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)
						&& key.startsWith(prefix)) {
					buffer.append(key).append("=").append(value).append("&");
				}
			}
		}
		String ret = buffer.toString();
		if (ret != null && ret.length() > 0) {
			ret = ret.substring(0, ret.length() - 1);
		}
		try {
			if (encoding != null && ret != null) {
				return URLEncoder.encode(ret, encoding);
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error(e);
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static String getAttributsByPrefix(HttpServletRequest request,
			String prefix, String encoding) {
		if (prefix == null || prefix.trim().length() == 0) {
			prefix = PARAM_PREFIX;
		}
		Enumeration enume = request.getAttributeNames();
		if (enume == null)
			return "";
		StringBuffer buffer = new StringBuffer();
		while (enume.hasMoreElements()) {
			String key = (String) enume.nextElement();
			if (!StringUtils.isEmpty(key) && key.startsWith(PARAM_PREFIX)) {
				Object object = request.getAttribute(key);
				if (object != null) {
					buffer.append(key).append("=").append(object.toString());
				}
			}
		}
		String ret = buffer.toString();
		if (ret != null && ret.length() > 0) {
			ret = ret.substring(0, ret.length() - 1);
		}
		try {
			if (encoding != null && ret != null) {
				return URLEncoder.encode(ret, encoding);
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error(e);
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static Map getAttrMapByPrefix(HttpServletRequest request,
			String prefix) {
		if (prefix == null || prefix.trim().length() == 0) {
			prefix = PARAM_PREFIX;
		}
		Enumeration enume = request.getAttributeNames();
		if (enume == null)
			return new HashMap();
		HashMap<String, Object> ret = new HashMap<String, Object>();
		while (enume.hasMoreElements()) {
			String key = (String) enume.nextElement();
			if (!StringUtils.isEmpty(key) && key.startsWith(PARAM_PREFIX)) {
				Object object = request.getAttribute(key);
				ret.put(key, object);
			}
		}
		return ret;
	}

	@SuppressWarnings("unchecked")
	public static String getQueryString(Map map, String encoding) {
		if (map == null || map.size() == 0) {
			return "";
		}

		StringBuffer buffer = new StringBuffer();
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			String key = (String) entry.getKey();
			Object value = entry.getKey();
			if (!StringUtils.isEmpty(key) && value != null) {
				buffer.append(key).append("=").append(value).append("&");
			}
		}

		String ret = buffer.toString();
		if (ret != null && ret.length() > 0) {
			ret = ret.substring(0, ret.length() - 1);
		}

		try {
			if (encoding != null && ret != null) {
				return URLEncoder.encode(ret, encoding);
			}
		} catch (UnsupportedEncodingException e) {
			LOG.error(e);
		}
		return ret;
	}

	public static String getCurrentURL(HttpServletRequest request) {
		if (request == null) {
			throw new IllegalArgumentException("Request is null!");
		}
		StringBuffer url = new StringBuffer();
		String appName = request.getContextPath();
		if (StringUtils.isNotEmpty(appName) && !appName.trim().equals("/")) {
			url.append(appName);
		}
		String path = request.getServletPath();
		if (StringUtils.isNotEmpty(path)) {
			url.append(path);
		}
		String queryString = request.getQueryString();
		if (StringUtils.isNotEmpty(queryString)) {
			url.append("?" + queryString);
		}
		return url.toString();
	}

}
